package org.example.xsda.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.xsda.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * OSS 工具类
 */
@Slf4j
@Component
public class OssUtil {

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;

    /**
     * 上传文件
     * @param file 文件
     * @param folder 文件夹路径
     * @return 文件访问URL
     */
    public String upload(MultipartFile file, String folder) throws IOException {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new RuntimeException("文件名不能为空");
        }

        // 生成唯一文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "") + extension;
        String objectName = folder + "/" + fileName;

        try (InputStream inputStream = file.getInputStream()) {
            // 上传文件到OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucketName(),
                    objectName,
                    inputStream
            );
            ossClient.putObject(putObjectRequest);

            // 返回文件URL
            return ossConfig.getUrlPrefix() + objectName;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败");
        }
    }

    /**
     * 删除文件
     * @param fileUrl 文件URL
     */
    public void delete(String fileUrl) {
        try {
            String objectName = fileUrl.replace(ossConfig.getUrlPrefix(), "");
            ossClient.deleteObject(ossConfig.getBucketName(), objectName);
        } catch (Exception e) {
            log.error("文件删除失败", e);
            throw new RuntimeException("文件删除失败");
        }
    }
}

